import 'package:book_app/feature/devices/view/note_form_widget.dart';
import 'package:book_app/product/db/devices_database.dart';
import 'package:book_app/product/models/device.dart';
import 'package:flutter/material.dart';

class DeviceDetail extends StatefulWidget {
  final Device? device;
  const DeviceDetail({super.key,this.device});

  @override
  State<DeviceDetail> createState() => _DeviceDetailState();
}

class _DeviceDetailState extends State<DeviceDetail> {
  final _formKey = GlobalKey<FormState>();
  late bool isImportant;
  late int number;
  late String title;
  late String description;

  @override
  void initState() {
    super.initState();

    // isImportant = widget.device?.isImportant ?? false;
    // number = widget.device?.number ?? 0;
    // title = widget.device?.title ?? '';
    // description = widget.device?.description ?? '';
  }
  @override
  Widget build(BuildContext context) => Scaffold(
    backgroundColor: Colors.black45,
    appBar: AppBar(
      actions: [buildButton()],
    ),
    body: Form(
      key: _formKey,
      child: NoteFormWidget(
        isImportant: isImportant,
        number: number,
        title: title,
        description: description,
        onChangedImportant: (isImportant) =>
            setState(() => this.isImportant = isImportant),
        onChangedNumber: (number) => setState(() => this.number = number),
        onChangedTitle: (title) => setState(() => this.title = title),
        onChangedDescription: (description) =>
            setState(() => this.description = description),
      ),
    ),
  );

  Widget buildButton() {
    final isFormValid = title.isNotEmpty && description.isNotEmpty;
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          foregroundColor: Colors.white,
          backgroundColor: isFormValid ? null : Colors.grey.shade700,
        ),
        onPressed: addOrUpdateDevice,
        child: const Text('Save'),
      ),
    );
  }

  void addOrUpdateDevice() async {
    final isValid = _formKey.currentState!.validate();

    if (isValid) {
      final isUpdating = widget.device != null;

      if (isUpdating) {
        await updateDevice();
      } else {
        await addDevice();
      }
      Navigator.of(context).pop();
    }
  }

  Future updateDevice() async {
    // final note = widget.device!.copy(
    //   isImportant: isImportant,
    //   number: number,
    //   title: title,
    //   description: description,
    // );
    //
    // await DevicesDatabase.instance.update(note);
  }

  Future addDevice() async {
    // final device = Device(
    //   title: title,
    //   isImportant: true,
    //   number: number,
    //   description: description,
    //   createdTime: DateTime.now(),
    // );
    // await DevicesDatabase.instance.create(device);
  }
}
